<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { Search, Plus, Download, Refresh, Edit, Delete } from '@element-plus/icons-vue';
import CustomerDialog from '@/components/CustomerDialog.vue';
import { dataAPI } from '@/http/leancloud';

/**
 * 此页面对应 客户管理
 */

// 查询条件
const queryForm = reactive({
  customerName: '', // 客户名称
  customerType: '', // 客户类型
  contactPerson: '', // 联系人
  contactPhone: '', // 联系电话
  status: '' // 状态
});

// 表格数据
const tableData = ref<any[]>([]);
// 表格加载状态
const loading = ref(false);
// 表格选中的行
const selectedRows = ref<any[]>([]);

// 分页参数
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
});

// 客户类型选项
const customerTypeOptions = [
  { value: 'enterprise', label: '企业客户' },
  { value: 'individual', label: '个人客户' },
  { value: 'agent', label: '代理商' }
];

// 状态选项
const statusOptions = [
  { value: 1, label: '正常' },
  { value: 0, label: '停用' }
];

// 获取表格数据
const fetchTableData = async () => {
  loading.value = true;
  try {
    const customers = await dataAPI.query('Customer');
    tableData.value = customers.map(customer => {
      // 确保status字段是数字类型
      const status = typeof customer.status === 'string' ? parseInt(customer.status) : customer.status;
      
      return {
        id: customer.objectId,
        customerName: customer.customerName,
        customerType: customer.customerType,
        contactPerson: customer.contactPerson,
        contactPhone: customer.contactPhone,
        contactEmail: customer.contactEmail,
        address: customer.address,
        creditLimit: customer.creditLimit,
        usedCredit: customer.usedCredit || 0,
        settlementCycle: customer.settlementCycle,
        status: status,
        remark: customer.remark,
        createTime: customer.createdAt ? new Date(customer.createdAt).toLocaleString() : '',
        updateTime: customer.updatedAt ? new Date(customer.updatedAt).toLocaleString() : ''
      };
    });
    pagination.total = customers.length;
  } catch (error) {
    console.error('获取客户数据失败:', error);
    ElMessage.error('获取数据失败');
  } finally {
    loading.value = false;
  }
};

// 重置查询条件
const resetQueryForm = () => {
  Object.keys(queryForm).forEach(key => {
    (queryForm as any)[key] = '';
  });
  handleSearch();
};

// 查询数据
const handleSearch = () => {
  pagination.currentPage = 1;
  fetchTableData();
};

// 处理表格选择变化
const handleSelectionChange = (rows: any[]) => {
  selectedRows.value = rows;
};

// 处理分页变化
const handlePageChange = (currentPage: number) => {
  pagination.currentPage = currentPage;
  fetchTableData();
};

// 处理每页条数变化
const handleSizeChange = (pageSize: number) => {
  pagination.pageSize = pageSize;
  pagination.currentPage = 1;
  fetchTableData();
};

// 对话框相关状态
const dialogVisible = ref(false);
const isEdit = ref(false);
const currentCustomer = ref<any>(null);

// 新增客户
const handleAdd = () => {
  isEdit.value = false;
  currentCustomer.value = null;
  dialogVisible.value = true;
};

// 编辑客户
const handleEdit = (row: any) => {
  isEdit.value = true;
  currentCustomer.value = { ...row };
  dialogVisible.value = true;
};

// 删除客户
const handleDelete = (row: any) => {
  ElMessageBox.confirm(
    `确定要删除客户"${row.customerName}"吗？`,
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    try {
      await dataAPI.delete('Customer', row.id);
      const index = tableData.value.findIndex(item => item.id === row.id);
      if (index > -1) {
        tableData.value.splice(index, 1);
        pagination.total--;
      }
      ElMessage.success('删除成功');
    } catch (error) {
      console.error('删除客户失败:', error);
      ElMessage.error('删除失败');
    }
  }).catch(() => {});
};

// 处理对话框确认
const handleDialogConfirm = async (data: any) => {
  try {
    if (isEdit.value) {
      // 编辑模式 - LeanCloud不支持直接更新，需要先获取对象再保存
      const customer = await dataAPI.get('Customer', currentCustomer.value.id);
      if (customer) {
        // 更新数据
        Object.assign(customer, data);
        await dataAPI.save('Customer', customer);
        
        // 更新本地数据
        const index = tableData.value.findIndex(item => item.id === currentCustomer.value.id);
        if (index > -1) {
          tableData.value[index] = {
            ...tableData.value[index],
            ...data,
            updateTime: new Date().toLocaleString()
          };
        }
      }
    } else {
      // 新增模式
      const savedCustomer = await dataAPI.save('Customer', data);
      if (savedCustomer) {
        const newCustomer = {
          id: savedCustomer.objectId,
          ...data,
          usedCredit: '0.00',
          createTime: new Date().toLocaleString(),
          updateTime: new Date().toLocaleString()
        };
        tableData.value.unshift(newCustomer);
        pagination.total++;
      }
    }
  } catch (error) {
    console.error('保存客户数据失败:', error);
    ElMessage.error('保存失败');
  }
};

// 导出数据
const exportData = () => {
  if (selectedRows.value.length === 0) {
    ElMessage.warning('请选择要导出的记录');
    return;
  }
  console.log('导出数据', selectedRows.value);
};

// 页面加载时获取数据
onMounted(() => {
  fetchTableData();
});
</script>

<template>
  <div class="customer-manage-view">
    <div class="page-header">
      <h2 class="page-title">客户管理</h2>
    </div>

    <!-- 搜索区域 -->
    <div class="search-container">
      <el-form :model="queryForm" inline>
        <el-form-item label="客户名称">
          <el-input v-model="queryForm.customerName" placeholder="请输入客户名称" clearable></el-input>
        </el-form-item>

        <el-form-item label="客户类型">
          <el-select v-model="queryForm.customerType" placeholder="请选择" clearable>
            <el-option
              v-for="item in customerTypeOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="联系人">
          <el-input v-model="queryForm.contactPerson" placeholder="请输入联系人" clearable></el-input>
        </el-form-item>

        <el-form-item label="联系电话">
          <el-input v-model="queryForm.contactPhone" placeholder="请输入联系电话" clearable></el-input>
        </el-form-item>

        <el-form-item label="状态">
          <el-select v-model="queryForm.status" placeholder="请选择" clearable>
            <el-option
              v-for="item in statusOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" :icon="Search" @click="handleSearch">查询</el-button>
          <el-button :icon="Refresh" @click="resetQueryForm">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 表格工具栏 -->
    <div class="table-toolbar">
      <div class="left">
        <el-button type="primary" :icon="Plus" @click="handleAdd">新增</el-button>
      </div>
      <div class="right">
        <el-button :icon="Download" @click="exportData">导出</el-button>
      </div>
    </div>

    <!-- 表格 -->
    <el-table
      v-loading="loading"
      :data="tableData"
      @selection-change="handleSelectionChange"
      style="width: 100%"
    >
      <el-table-column type="selection" width="55" />
      <el-table-column prop="customerName" label="客户名称" width="150" />
      <el-table-column prop="customerType" label="类型" width="100">
        <template #default="{ row }">
          <el-tag
            :type="row.customerType === 'enterprise' ? 'success' : row.customerType === 'individual' ? 'warning' : 'info'"
          >
            {{ customerTypeOptions.find(item => item.value === row.customerType)?.label }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="contactPerson" label="联系人" width="100" />
      <el-table-column prop="contactPhone" label="联系电话" width="130" />
      <el-table-column prop="contactEmail" label="邮箱" width="180" show-overflow-tooltip />
      <el-table-column prop="address" label="地址" min-width="200" show-overflow-tooltip />
      <el-table-column prop="settlementCycle" label="结算周期" width="120" />
      <el-table-column prop="creditLimit" label="信用额度" width="120">
        <template #default="{ row }">
          {{ row.creditLimit }}
        </template>
      </el-table-column>
      <el-table-column prop="usedCredit" label="已用额度" width="120">
        <template #default="{ row }">
          {{ row.usedCredit }}
        </template>
      </el-table-column>
      <el-table-column prop="status" label="状态" width="100">
        <template #default="{ row }">
          <el-tag :type="row.status == 1 ? 'success' : 'danger'">
            {{ statusOptions.find(item => item.value == row.status)?.label || `未知状态(${row.status})` }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="createTime" label="创建时间" width="180" />
      <el-table-column label="操作" fixed="right" width="150">
        <template #default="{ row }">
          <el-button type="primary" link :icon="Edit" @click="handleEdit(row)">编辑</el-button>
          <el-button type="danger" link :icon="Delete" @click="handleDelete(row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination-container">
      <el-pagination
        v-model:current-page="pagination.currentPage"
        v-model:page-size="pagination.pageSize"
        :page-sizes="[10, 20, 50, 100]"
        :total="pagination.total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handlePageChange"
      />
    </div>

    <!-- 客户对话框 -->
    <CustomerDialog
      v-model:visible="dialogVisible"
      :customer-data="currentCustomer"
      :is-edit="isEdit"
      @confirm="handleDialogConfirm"
    />
  </div>
</template>

<style scoped>
.customer-manage-view {
  padding: 20px;
}

.page-header {
  margin-bottom: 20px;
}

.page-title {
  font-size: 20px;
  font-weight: 500;
  margin: 0;
}

.search-container {
  background-color: #fff;
  padding: 20px;
  border-radius: 4px;
  margin-bottom: 20px;
}

.table-toolbar {
  display: flex;
  justify-content: space-between;
  margin-bottom: 20px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}
</style>